<?php
/**
 * Created by WarCraft3
 * User: WarCraft3
 * Date: 2021/8/12
 * Time: 10:33
 */

namespace app\api\controller;


use app\admin\model\ExamItem;
use app\common\controller\Api;
use app\common\controller\Redis;
use think\Db;
use app\admin\model\Avideo as Avideos;
use app\admin\model\Auser;
use think\Exception;
use think\exception\PDOException;

class Avideo extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    private $_uid;

    protected function _initialize()
    {
        parent::_initialize();
        $jwt = $this->request->header('Authorization');
        if ($jwt) {
            $this->check_token($jwt);
            $this->_uid = $this->_token['uid'];

        } else {
            $this->success('缺少token', '', '401');
        }
    }

    /*
     * 获取我的视频列表
     * */
    public function getv()
    {
        $uid = $this->_uid;
        $type = $this->request->param('type') ?? '0';
        $cate = Db::name('auser')->where('id', $uid)->value('jobs_id');//获取用户所属部门
        $page = $this->request->param('page') ?? 1;
        $num = $this->request->param('num') ?? 5;
        $data = $this->getVideo($cate,$type,$page,$num);
        $this->success('成功', $data);
    }

    /*
     * 模糊搜索视频
     * */
    public function selv()
    {
        $key = $this->request->param('keyword');
        $page = $this->request->param('page') ?? 1;
        $num = $this->request->param('num') ?? 15;
        if (!$key)$this->error('缺少参数');
        $cate_id = Db::name('auser')->where('id',$this->_uid)->value('jobs_id');
        $data = $this->getVideo($cate_id,'',$page,$num,$key);
        $this->success('成功', $data);
    }
    /**
     *  我的收藏->搜索视频
     */
    public function mysearchVideos()
    {
        $key = $this->request->param('keyword');
        $page = $this->request->param('page') ?? 1;
        $num = $this->request->param('num') ?? 15;
        $type = $this->request->param('type');
        $cate_id = Db::name('auser')->where('id',$this->_uid)->value('jobs_id');
        if($type=='colles'){
            $vids = Db::name('colles')->where('auser_id',$this->_uid)->column('avideo_id');
        }else{
            $vids = Db::name('zans')->where('auser_id',$this->_uid)->column('avideo_id');
        }
        //2,根据视频id , 查询所有的视频信息
        $videos = $this->getVideo($cate_id,'',$page,$num,$key,$vids);
        $this->success('搜索收藏视频',$videos);
    }
    /*
     * 获取视频信息---统一封装
     * @param $cate_id int  视频分类id
     * @param $type int  视频所属类型   0=必修,1=选修,2=推荐
     * */
    private function getVideo($cate_id = '', $type= '' , $page= 1 ,$num= 10,$key='',$avideo_id=null)
    {
        $where_cate = null;

        if ($avideo_id){
            $where_cate['avideo.id']= ['in',$avideo_id];
        }
        $where_type = null;
        if ($type){
            $where_type['avideo.type']= $type;
        }
        $redis = Redis::getInstance()->getRedisConn();
        $re = $redis->hGetAll('user_'.$this->_uid);
        $vidnots=is_del_avideo($this->_uid);
        $vmodel = new \app\admin\model\Avideo();
        $data = $vmodel::with([
                'com' => function($query) {
                    $query->order('id','desc') ;
                }
            ])->with('category')
            ->where('avideo.name|avideo.intro','like','%'.$key.'%')
            ->where($where_cate)
            ->whereNotIn('avideo.id',$vidnots)
            ->where($where_type)
            ->select()->each(function ($item) use($re){
                if (sizeof($item['com']) > 0) {
                    $item['comments'] = sizeof($item['com']);
                    //查询评论人信息
                    foreach ($item['com'] as $k => $v) {
                        $user = \app\admin\model\Auser::get($v['auser_id']);
                        $item['com'][$k]['name'] = $user['name'];
                        $item['com'][$k]['avatar'] = $user['avatar'];
                    }
                    $coms=$item['com'];
                    $commms=[];
                    foreach ($item['com'] as $k => $v){
                        if($item['com'][$k]['pid']>0){
                            unset($item['com'][$k]);
                        }else{
                            $arr=[];
                            foreach ($coms as $ve) {
                                if ($ve['pid'] == $item['com'][$k]['id']) {
                                    $arr[] = $ve;
                                };
                            };
                            $item['com'][$k]['children']=$arr;
                            $commms[]=$item['com'][$k];
                        }
                    }
                    $item['com']=$commms;
                }else{
                    $item['comments'] = 0;
                }

                $item['ptype'] = '2'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item['ptype'] = $vv;
                    }
                }

                return $item;
            })->toArray();
        if ($cate_id){
            $cateids=pid_cate($cate_id);
            foreach ($data as $k=>$v){
                $cates=explode(',',$data[$k]['cate_id']);
                if(empty(array_intersect($cateids,$cates))){
                    unset($data[$k]);
                }
            }
        }
        $data=page_array($num,$page,$data);
        return $data;
    }

    /**
     * 删除视频,相当于隐藏只针对视频.
     */
    public function delete_avideo(){
        $vid = $this->request->param('vid'); //视频id
        $redis = Redis::getInstance()->getRedisConn();
        $reds=$redis->hGetAll('user_'.$this->_uid);
        if(empty($vid)){
            $this->error('参数错误');
        }
        if(empty($reds[$vid])){
            $this->error('该视频未完成');
        }
        $redis = Redis::getInstance()->getRedisConn();
        $isres = $redis->hExists('user_avudeo_'.$this->_uid, $vid);
        $redis->hSet('user_avudeo_'.$this->_uid, $vid, '1');
        if(!$isres){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /*
     * 观看完毕后
     * 1, 存储到redis中hash表 , 用户id是表名 , key是视频id value是观看状态
     * 2, 学分是必修视频和考试获取 ,  积分是看视频就有累计时长,可以攒积分
     * */
    public function readed()
    {
        $status = $this->request->param('status'); // 0=观看中, 1=已看完
        $vid = $this->request->param('vid'); //视频id
        $vtype = $this->request->param('type');// 视频类型 0=必修,1=选修,2=推荐
        $vtime = $this->request->param('vtime'); //视频时长

        //根据当前视频所属的部门 和 当前观看视频用户所属的部门 , 查看是否为一个部门, 如果是说明是用户需要看的必选/选秀/推荐视频等
        $mycate = Db::name('auser')->where('id',$this->_uid)->value('jobs_id');
        $vcate = Db::name('avideo')->where('id',$vid)->value('cate_id');

        $cateids=pid_cate($mycate);//用户的部门id到公司层级
        $cates=explode(',',$vcate);//视频是多个部门
        //1,创建/更新视频记录
        $redis = Redis::getInstance()->getRedisConn();
        $isres = $redis->hExists('user_'.$this->_uid, $vid);
        $redis->hSet('user_'.$this->_uid, $vid, $status);
        if(!$isres){
            $model = new Auser();
            $vmod = new Avideos();
            $vinfo = $vmod::get($vid);
            //2,增加学时 , 积分 等
            Db::startTrans();
            switch ($vtype) {
                case '0':
                    $vmod->where('id', $vid)->setInc('shows');
                    $model->where('id', $this->_uid)->setInc('longs', $vtime);
                    $this->precord('','',2,$this->_uid,$vid,$vtime,$vtype);
                    if (!empty(array_intersect($cateids,$cates))){ //说明视频 和 我的部门 是一个, 并且是必修视频 , 那么去增加积分等
                        //必修视频, 增加学分 , 积分, 累计时长
                        try {
                            $model->where('id', $this->_uid)->setInc('ji_fen', $vinfo->ji_fen);
                            $model->where('id', $this->_uid)->setInc('all_fen', $vinfo->ji_fen);
                            $model->where('id', $this->_uid)->setInc('xue_fen', $vinfo->xue_fen);
                            $this->precord($vinfo->ji_fen,'',0,$this->_uid,$vid,0,$vtype);
                            $this->precord('',$vinfo->xue_fen,1,$this->_uid,$vid,0,$vtype);
                            Db::commit();
                        } catch (PDOException $E) {
                            Db::rollback();
                            $this->error($E->getMessage());
                            break;
                        } catch (Exception  $e) {
                            Db::rollback();
                            $this->error($e->getMessage());
                            break;
                        }
                    }
                    Db::commit();
                    break;
                default:
                    try {
                        //其他类型只增加 积分 和 时长
                        $model->where('id', $this->_uid)->setInc('ji_fen', $vinfo->ji_fen);
                        $model->where('id', $this->_uid)->setInc('all_fen', $vinfo->ji_fen);
                        $this->precord($vinfo->ji_fen,'',0,$this->_uid,$vid,0,$vtype);
                        $this->precord('','',2,$this->_uid,$vid,$vtime,$vtype);
                        $model->where('id', $this->_uid)->setInc('longs', $vtime);
                        $vmod->where('id', $vid)->setInc('shows');
                        Db::commit();
                    } catch (PDOException $E) {
                        Db::rollback();
                        $this->error($E->getMessage());
                        break;
                    } catch (Exception  $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                        break;
                    }
                    break;
            }
            $this->success('ok');
        }
    }

    /**
     * 结束观看,看完所有必 修视频后，提醒“恭喜完成本月学习任务”自动生成结业证书
     */
    public function endavideo(){
        $uid=$this->_uid;
        $status = $this->request->param('status'); // 0=观看中, 1=已看完
        $vid = $this->request->param('vid'); //视频id
        $vtype = $this->request->param('type');// 视频类型 0=必修,1=选修,2=推荐
        $avideo=Db::name('avideo')->where('id',$vid)->find();
        if(!$avideo){
            $this->error('不存在这个视频');
        }
        if(!empty($avideo['type'])){
            $this->error('视频不是必修');
        }
        if($status==1&&$vtype==0){
            $period_id=$avideo['period_id'];
            $avideo_kekan_ids=cate_avideo($this->_uid);//所有可看视频
            $avideo_ids=Db::name('avideo')->where('period_id',$period_id)->whereIn('id',$avideo_kekan_ids)->column('id');
            $yiguankan_ids=Db::name('point')->where('type',1)->where('auser_id',$uid)->column('avideo_id');
            if (array_values($avideo_ids) == array_values(array_intersect($yiguankan_ids, $avideo_ids))) {
                $auser=Db::name('auser')->where('id',$uid)->find();
                if(!empty($auser['period_ids'])){
                    $ids=explode(',',$auser['period_ids']);
                    if(!in_array($period_id,$ids)){
                        $data['period_ids']=$auser['period_ids'].','.$period_id;
                        Db::name('auser')->where('id',$uid)->update($data);
                        $this->success('恭喜完成本月学习任务');
                    }else{
                        $this->error('任务已完成');
                    }
                }else{
                    $data['period_ids']=$period_id;
                    Db::name('auser')->where('id',$uid)->update($data);
                    $this->success('恭喜完成本月学习任务');
                }
            }else {
                $this->error('本月视频还没看完');
            }
        }else{
            $this->error('视频不是必修');
        }
    }
    /*
     * 添加学分 积分等获取记录
     * */
    private function precord($jifen = '',$xuefen='',$type,$auser_id,$avideo_id,$vtime=0,$xiu_type=0)
    {
        $is=null;
        if ($type == 0){
            $is = Db::name('point')->where(['auser_id'=>$this->_uid,'avideo_id'=>$avideo_id])->where('type','0')->find();
        }elseif ($type == 1){
            $is = Db::name('point')->where(['auser_id'=>$this->_uid,'avideo_id'=>$avideo_id])->where('type','1')->find();
        }

        if (!$is){
            $data['ctime'] = date('Y-m-d H:i:s',time());
            $data['jifen'] = $jifen;
            $data['xuefen'] = $xuefen;
            $data['type'] = $type;
            $data['auser_id'] = $auser_id;
            $data['avideo_id'] = $avideo_id;
            $data['longs'] = $vtime;
            $data['xiu_type'] = $xiu_type;
            Db::name('point')->insert($data);
        }
    }


    /*
     * 获取视频对应的考试
     * */
    public function videoToExam()
    {
        $vid = $this->request->param('vid');
        $vmodel = new Avideos();
        $ret = $vmodel::with('exam')->order('id','desc')->where('id',$vid)->find()->toArray();
        if ($ret['exam'] == null){
            $this->error('此视频无考试');
        }
        $exam_third_count=Db::name('exam_third')->where('avideo_id',$vid)->where('auser_id',$this->_uid)->count();
        if($exam_third_count>=3){
            $this->error('已考试通过三次');
        }
        $ret['needtime'] = $ret['exam']['needtime'];
        //判断此人对应此考试 是否已通过, 或者 未通过  未考试
        $exc = Db::name('exam_record')->where(['auser_id'=>$this->_uid,'exam_id'=>$ret['exam']['id']])->where('ispass','1')->find();
        if ( $exc ){
            $arr = json_decode($exc['record'],1);
            $exitem = new ExamItem();
            foreach ($arr as  $k=>$v){
                $arr[$k]['info'] = $exitem::get($v['id']);
                $arr[$k]['isState'] = ['duiOrCuo'=>$v['duiOrCuo']];
            }
            $exc['record'] = $arr;
            $exc['tifen'] = $ret['exam']['tifen'];
            $exc['intro'] = $ret['intro'];
            $this->success('已通过此考试,直接跳转考试页面或者弹框提示已通过此考试',$exc,'2');
        }

        if ($ret['exam']){
            //查询考试试题
            $ret['exam_item'] = Db::name('exam_item')->where('exam_id',$ret['exam']['id'])->select()->toArray();
            foreach ( $ret['exam_item'] as $k=>$v ){
                $ret['exam_item'][$k]['Lstate'] = false;

                $ret['exam_item'][$k]['answers'][0]['key'] = 'A';
                $ret['exam_item'][$k]['answers'][0]['value'] = $v['A'];
                //$ret['exam_item'][$k]['answers'][0]['ischeck'] = false;

                $ret['exam_item'][$k]['answers'][1]['key'] = 'B';
                $ret['exam_item'][$k]['answers'][1]['value'] = $v['B'];
//                $ret['exam_item'][$k]['answers'][1]['ischeck'] = false;

                $ret['exam_item'][$k]['answers'][2]['key'] = 'C';
                $ret['exam_item'][$k]['answers'][2]['value'] = $v['C'];
//                $ret['exam_item'][$k]['answers'][2]['ischeck'] = false;

                $ret['exam_item'][$k]['answers'][3]['key'] = 'D';
                $ret['exam_item'][$k]['answers'][3]['value'] = $v['D'];
//                $ret['exam_item'][$k]['answers'][3]['ischeck'] = false;

                if ($v['E'] == ''){
                    unset($ret['exam_item'][$k]['E']);
                }else{
                    $ret['exam_item'][$k]['answers'][4]['key'] = 'E';
                    $ret['exam_item'][$k]['answers'][4]['value'] = $v['E'];
//                    $ret['exam_item'][$k]['answers'][4]['ischeck'] = false;

                }

                if ($v['F'] == ''){
                    unset($ret['exam_item'][$k]['F']);
                }else{
                    $ret['exam_item'][$k]['answers'][5]['key'] = 'F';
                    $ret['exam_item'][$k]['answers'][5]['value'] = $v['F'];
//                    $ret['exam_item'][$k]['answers'][5]['ischeck'] = false;
                }
            }
        }
        $ret['exam_new'] = $ret['exam'];
        $this->success('成功',$ret);
    }
    /*
     * 获取指定分类下的视频
     * */
    public function cateVideo()
    {
        $cate_id = $this->request->param('cid');
        if(!$cate_id) $this->error('缺少参数cid');
        $data = $this->getVideo($cate_id);
        $cate_info = Db::name('category')->where('id',$cate_id)->field('name,image')->find();
        $ret['cate'] = $cate_info;
        if (count($data)){
            $ret['arr'] = $data;
            $this->success('成功',$ret);
        }
        $this->error('无数据',[]);
    }

    /*
     * 点赞视频
     * */
    public function zansVideo()
    {
        $vid = $this->request->param('vid');
        Db::startTrans();
        try{
            Db::name('zans')->insertGetId(['auser_id'=>$this->_uid,'avideo_id'=>$vid]);
            Db::name('avideo')->where('id',$vid)->setInc('zans');
            Db::commit();
            $this->success('点赞成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }

    }
    /*
     * 取消点赞
     * */
    public function cancelzans()
    {
        $vid = $this->request->param('vid');
        Db::startTrans();
        try{
            Db::name('zans')->where(['auser_id'=>$this->_uid,'avideo_id'=>$vid])->delete();
            Db::name('avideo')->where('id',$vid)->setDec('zans');
            Db::commit();
            $this->success('取消成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }
    }

    /**
     * 收藏视频
     */
    public function collesVideo()
    {
        $vid = $this->request->param('vid');
        Db::startTrans();
        try{
            Db::name('colles')->insertGetId(['auser_id'=>$this->_uid,'avideo_id'=>$vid]);
            Db::name('avideo')->where('id',$vid)->setInc('colles');
            Db::commit();
            $this->success('收藏成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }

    }

    /**
     * 取消收藏
     */
    public function cancelcolles()
    {
        $vid = $this->request->param('vid');
        Db::startTrans();
        try{
            Db::name('colles')->where(['auser_id'=>$this->_uid,'avideo_id'=>$vid])->delete();
            Db::name('avideo')->where('id',$vid)->setDec('colles');
            Db::commit();
            $this->success('取消成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }
    }
    /*
     * 评论视频
     * */
    public function pingVideo()
    {
        $vid = $this->request->param('vid');
        $says = $this->request->param('says');
        $pid = $this->request->param('pid');
        $talk_pid = $this->request->param('talk_pid');
        if(empty($pid)){
            $pid=0;
        }
        if(empty($talk_pid)){
            $talk_pid=0;
        }
        Db::startTrans();
        try{
            Db::name('comments')->insertGetId(['says'=>$says,'auser_id'=>$this->_uid,'avideo_id'=>$vid,'pid'=>$pid,'talk_pid'=>$talk_pid]);
            Db::commit();
            $this->success('评论成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }
    }

    /*
     * 点赞收藏 资料
     * */
    public function zfile()
    {
        $vid = $this->request->param('vid');
        $ret = Db::name('zansfile')->where(['auser_id'=>$this->_uid,'avfile_id'=>$vid])->find();
        if ($ret){
            $this->success('已点赞,请勿重复');
        }
        Db::startTrans();
        try{
            Db::name('zansfile')->insertGetId(['auser_id'=>$this->_uid,'avfile_id'=>$vid]);
            Db::commit();
            $this->success('点赞成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }
    }
    /*
     * 取消点赞收藏 资料
     * */
    public function cancelzfile()
    {
        $vid = $this->request->param('vid');
        Db::startTrans();
        try{
            Db::name('zansfile')->where(['auser_id'=>$this->_uid,'avfile_id'=>$vid])->delete();
            Db::commit();
            $this->success('取消成功');
        }catch(PDOException $e){
            Db::rollback();
            $this->error('失败');
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }

    }
    /*
        * 获取视频资料
        * */
    public function vfile()
    {
        $vid = $this->request->param('vid');
        $arr = Db::name('avfile')->where('avideo_id',$vid)->select()->each(function ($item) use($vid){
            $item['iszan'] = 0;
            $is = Db::name('zansfile')->where(['auser_id'=>$this->_uid,'avfile_id'=>$item['id']])->find();
            if($is){
                $item['iszan'] = 1;
            }
            return $item;
        });
        if (sizeof($arr) > 0){
            $this->success('成功',$arr);
        }
        $this->success('无数据');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 资料
     */
    public function files()
    {
        $cateid = $this->request->param('cateid');
        $arr = Db::name('avfile')->where('avfilecate_id',$cateid)->order('weigh','desc')->select()->each(function ($item){
            $item['iszan'] = 0;
            $is = Db::name('zansfile')->where(['auser_id'=>$this->_uid,'avfile_id'=>$item['id']])->find();
            if($is){
                $item['iszan'] = 1;
            }
            return $item;
        });
        if (sizeof($arr) > 0){
            $this->success('成功',$arr);
        }
        $this->success('无数据');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 资料分类
     */
    public function filecate()
    {
        $arr = Db::name('avfilecate')->where('status',1)->order('weigh','desc')->select()->each(function ($item){
            $item['image']=IMG.$item['image'];
            return $item;
        });
        if (sizeof($arr) > 0){
            $this->success('成功',$arr);
        }
        $this->success('无数据');
    }
    /*
 * 点击某个视频, 跳转所属视频合集
 * */
    public function vcollect()
    {
        $vid = $this->request->param('vid');
        $cid = Db::name('avideo')->where('id',$vid)->find();
        if (!$cid){
            $this->error('此视频不存在');
        }
        $col = Db::name('col')->find($cid['col_id']);
        if (!$col){
            $this->error('无此合集');
        }
        $avideo_ids=cate_avideo($this->_uid);//所有可看视频
        $vidnots=is_del_avideo($this->_uid);//已删除视频
        $count = Db::name('avideo')->where('col_id',$col['id'])->whereIn('id',$avideo_ids)->whereNotIn('id',$vidnots)->count();
        $cate = Db::name('auser')->where('id', $this->_uid)->value('jobs_id');//获取用户所属部门
        $vids = Db::name('avideo')->where('col_id',$col['id'])->column('id');
        $ret['count'] = $count;//合集总数
        $ret['name'] = $col['name'];//合集名称
        $ret['videos'] = $this->getVideo($cate,'','',1000,'',$vids);
        $this->success('ok',$ret);
    }
}